package com.ztesoft.huangfu.learning.springboot.springbootaop.aspact;

import com.ztesoft.huangfu.learning.springboot.springbootaop.annotation.UserAccess;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/6/10
 * Time: 10:44
 * Version: 1.0
 * Description:
 **/
@Component
@Aspect
public class UserAccessAspect {
    //    @Pointcut(value = "@annotation(com.ztesoft.huangfu.learning.springboot.springbootaop.annotation.UserAccess)")
//    public void access() {
//    }
//
//    @Before("access()")
//    public void deBefore(JoinPoint joinPoint) throws Throwable {
//        System.out.println("second before");
//    }
    //拦截包下的所有public注解修饰的方法
    @Around("execution(@com.ztesoft.huangfu.learning.springboot.springbootaop.annotation.*  public * *(..))")
    public Object around(ProceedingJoinPoint pjp) {
        //拦截UserAccess注解的方法
//        @Around("@annotation(userAccess)")
//        public Object around (ProceedingJoinPoint pjp, UserAccess userAccess){
        //获取注解里的值
//            System.out.println("second around:" + userAccess.desc());
        System.out.println("pjp.getArgs():" + pjp.getArgs());
        try {
            System.out.println("前置鉴权方法");

            // 调用方法的参数
            Object[] args = pjp.getArgs();
            // 调用的方法名 两种
            String method = pjp.getSignature().getName();
            MethodSignature signature =(MethodSignature) pjp.getSignature();
            Method method2 = signature.getMethod();
            //获取方法注解如果方法么有这个注解，就返回空
            UserAccess userAccess = method2.getAnnotation(UserAccess.class);

            Annotation[] annot = pjp.getSignature().getClass().getAnnotations();
            // 获取目标对象
            Object target = pjp.getTarget();
            // 执行完方法的返回值：调用proceed()方法，就会触发切入点方法执行
            //这里可以根据需求对args入参重组
//            args[0] = "qwe";
            Object obj = pjp.proceed(args);

            System.out.println("后置日志方法");
            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
}
